package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.manage.domain.db.Question;
import com.tanhua.manage.domain.db.UserInfo;
import com.tanhua.manage.domain.mongo.RecommendUser;
import com.tanhua.manage.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RecommendUserService {

    @Reference
    private RecommendUserApi recommendUserApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private UserLocationApi userLocationApi;

    /**
     * 查询今日佳人
     * @return
     */
    public RecommendUserVo todayBest() {
        //1. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        //2. 调用api查询今日佳人
        RecommendUser todayBest = recommendUserApi.todayBest(userId);

        // 没有推荐用户
        if (null == todayBest){
            todayBest = new RecommendUser();
            todayBest.setUserId(RandomUtils.nextLong(1,99));// 1-99 都是客服
            todayBest.setScore(RandomUtils.nextDouble(60,80));// 随机缘分值
        }
        //3. 通过佳人id查询佳人详情
        UserInfo userInfo = userInfoApi.findById(todayBest.getUserId());
        //4. 构建vo
        RecommendUserVo vo = new RecommendUserVo();
        // 复制属性
        BeanUtils.copyProperties(userInfo,vo);
        // tags处理
        vo.setTags(StringUtils.split(userInfo.getTags(),","));
        // 缘分值
        vo.setFateValue(todayBest.getScore().longValue());
        return vo;
    }

    /**
     * 推荐列表
     * @param queryParam
     * @return
     */
    public PageResult<RecommendUserVo> recommendList(RecommendUserQueryParam queryParam) {
        //根据token查询当前登录的用户信息
        Long userId = UserHolder.getUserId();
        //调用api查询推荐数据
        PageResult result = recommendUserApi.findPage(queryParam.getPage(),queryParam.getPagesize(),userId);
        List<RecommendUser> records = result.getItems();
        if (CollectionUtils.isEmpty(records)){
            //如果结果集是空的（没有推荐） ，就推荐默认的客服人员
            result.setCounts(10L);
            result.setPages(1L);
            records = defultRecommend();

        }
        List<RecommendUserVo> recommendUsers = new ArrayList<>();
        for (RecommendUser record : records) {

            RecommendUserVo best = new RecommendUserVo();
            UserInfo userInfo = userInfoApi.findById(record.getUserId());

            BeanUtils.copyProperties(userInfo,best);
            best.setFateValue(record.getScore().longValue());
            best.setTags (StringUtils.split(userInfo.getTags(),","));

            recommendUsers.add(best);

        }
        result.setItems(recommendUsers);
        return result;
    }


    /**
    构造默认数据
     */
    private List<RecommendUser> defultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";

        List<RecommendUser> records = new ArrayList<>();
        for (String id : ids.split(",")) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setScore(RandomUtils.nextDouble(70,98));
            records.add(recommendUser);
        }
        return records;
    }

    /**
     * 查看佳人信息
     * @param userId
     * @return
     */
    public RecommendUserVo getPersonalInfo(Long userId) {
        //1. 查询登陆用户与佳人的缘分值
        Long loginUserId = UserHolder.getUserId();
        Double score = recommendUserApi.queryForScore(loginUserId,userId);

        //2. 查询佳人的详情
        UserInfo userInfo = userInfoApi.findById(userId);
        //3. 转vo
        RecommendUserVo vo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo,vo);
        vo.setTags(StringUtils.split(userInfo.getTags()));
        vo.setFateValue(score.longValue());
        //4. 返回
        return vo;
    }

    /**
     * 查看佳人陌生人问题
     * @param userId
     * @return
     */
    public String strangerQuestions(Long userId) {
        //1. 调用api，通过userId查询佳人的陌生人问题设置
        Question question = questionApi.findByUserId(userId);
        //如果没有设置，使用默认值
        if (null == question){
            return "你喜欢我吗？";
        }
        return question.getTxt();
    }

    /**
     * 回复佳人陌生人问题
     * @param paramMap
     * @return
     */
    public void replyStrangerQuestions(Map<String, Object> paramMap) {
        //1.取佳人id
        Integer userId = (Integer) paramMap.get("userId");
        //2.回复内容
        String reply = (String) paramMap.get("reply");

        //获取登录用户的名字
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        String nickname = userInfo.getNickname();

        //获取对方设置的问题
        String question = questionApi.findByUserId(userId.longValue()).getTxt();

        //构建环信消息
        Map<String , Object> msgMap = new HashMap<>();
        msgMap.put("userId", UserHolder.getUserId());// 发送者id
        msgMap.put("nickname",nickname); // 发送者的昵称
        msgMap.put("strangerQuestion", question);
        msgMap.put("reply", reply);

        //调用环信发送消息
        huanXinTemplate.sendMsg(userId.toString(), JSON.toJSONString(msgMap));
    }

    /**
     * 搜附近
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> searchNearBy(String gender, Long distance) {
        //获取登录者id
        Long loginUserId = UserHolder.getUserId();
        //调用api查询附近的人
        List<UserLocationVo> userLocationList =userLocationApi.searchNearBy(loginUserId,distance);
        List<NearUserVo> voList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userLocationList)){
            List<Long> userIds = userLocationList.stream().map(UserLocationVo::getUserId).collect(Collectors.toList());
            List<UserInfo> userInfoList = userInfoApi.findByBatchId(userIds);
            //性别顾虑，并转成vo，filter（条件满足保留）
            voList = userInfoList.stream().filter(userInfo -> userInfo.getGender().equals(gender)).map(userInfo -> {
                NearUserVo nearUserVo = new NearUserVo();
                BeanUtils.copyProperties(userInfo,nearUserVo);
                nearUserVo.setUserId(userInfo.getId());
                return nearUserVo;
            }).collect(Collectors.toList());
        }
        return voList;
    }
}
